﻿const authorized_key = "authorized"
const refToken_key = "refToken_key"
// 保存Bearer到localStorage
function setItem(authorized) {
    localStorage.setItem(authorized_key, JSON.stringify(authorized));
}
function setRefToken(refToken) {
    localStorage.setItem(refToken_key, JSON.stringify(refToken));
}
// 从localStorage获取Bearer
function getItem() {
    return JSON.parse(localStorage.getItem(authorized_key));
}
function getRefToken() {
    return JSON.parse(localStorage.getItem(refToken_key));
}
// 移除Bearer
function removeItem() {
    localStorage.removeItem(authorized_key);
    localStorage.removeItem(refToken_key);
}
// 清空本地缓存
function clear() {
    localStorage.clear();
}

//const Bearer = {
//    "Bearer": {
//        "name": "Bearer",
//        "schema": {
//            "type": "apiKey",
//            "description": "请输入Login接口返回的Token，前置Bearer。示例：Bearer {Token}",
//            "name": "Authorization",
//            "in": "header"
//        },
//        "value": ""
//    }
//}

// 拦截登录和刷新Token请求，将token保存到本地
const originalFetch = window.fetch;
window.fetch = async (...args) => {
    // 在发起请求前进行操作
    const [resource, config] = args;

    // 如果不是login，则在请求头添加 Authorization
    //if (!config.url.includes("/api/Auth/Login")) {
    //    const token = getJwtToken()
    //    if (token && !config.headers.Authorization) {
    //        const authorization = 'Bearer ' + token;
    //        config.headers = { ...config.headers, Authorization: authorization }
    //    }
    //}

    // 调用原始 fetch 函数
    const response = await originalFetch(resource, config);

    // 不能直接进行响应，需要深复制response，
    const clonedResponse = response.clone();

    // 在接收到响应后进行操作
    if (clonedResponse.url.includes("/api/Auth/Login")) {
        let authorized = getItem();
        clonedResponse.json().then(res => {
            if (res.isSuccess) {
                if (authorized) {
                    authorized = { Bearer: { ...authorized.Bearer, value: 'Bearer ' + res.data.accessToken } }
                    setItem(authorized)
                } else {
                    authorized = { Bearer: {value: 'Bearer ' + res.data.accessToken } }
                    setItem(authorized)
                }
                setRefToken(res.data.refreshToken)
                // 刷新
                window.location.reload()
            }
        })
    }
    // 在接收到响应后进行操作
    if (clonedResponse.url.includes("/api/Auth/RefreshToken")) {
        let authorized = getItem();
        clonedResponse.json().then(res => {
            if (res.isSuccess) {
                authorized = { Bearer: { ...authorized.Bearer, value: 'Bearer ' + res.data } }
                setItem(authorized)
                // 刷新
                window.location.reload()
            }
        })
    }

    return response;
};